<template>
	<uni-file-picker
		file-mediatype="image"
		file-extname="png,jpg" 
		:limit="limit" 
		:auto-upload="false"
		:value="filePathsList"
		@progress="progress" 
		@success="success" 
		@fail="fail"
		@select="handleSelect" 
		@delete="deleteSelect"
	></uni-file-picker>
</template>

<script>
	import {getToken} from "../../../apis/myCookie.js"
	import {addBusiness} from "../../../apis/business.js"
	
	export default{
		props: {
			limit:{
				type:Number,
				default:1
			},
			
		},
		data(){
			return{
				filePathsList: [],
				uploadPathList: [],
			}
		},
		methods:{
			select(e){
				console.log('选择文件：',e)
			},
			// 获取上传进度
			progress(e){
				console.log('上传进度：',e)
			},
			
			// 上传成功
			success(e){
				console.log('上传成功')
			},
			
			// 上传失败
			fail(e){
				console.log('上传失败：',e)
			},
			async handleSelect(res) {
				 await this.uploadImg(res.tempFilePaths);
				 // console.log(this.uploadPathList);
				 this.$emit("uploadFile",this.uploadPathList.join(","));
			},
			async uploadImg(tempFilePaths) {
			    if (!tempFilePaths.length) return;
			    const path = tempFilePaths.pop();
			    this.filePathsList.push({url:path,name:""})
			    let [err, {data}] = await uni.uploadFile({
			        url: 'http://localhost:8080/common/upload',
			        filePath: path,
			        name: 'file',
			        header: {
			            'Authorization': 'Bearer ' + getToken(),
			            "Content-Type": "multipart/form-data",
			        }
			    });
			    
				data = JSON.parse(data);

			    // upload success
			    this.filePathsList[this.filePathsList.length - 1].name = data
				this.uploadPathList.push(data.fileName);
			    this.uploadImg(tempFilePaths);
			},
			deleteSelect(err) {
				const num = this.filePathsList.findIndex(v => v.url === err.tempFilePath);
				this.filePathsList.splice(num, 1);
				this.uploadPathList.splice(num, 1);
				this.$emit("uploadFile",this.uploadPathList.join(","));
			},
		}
	}
</script>

<style>
</style>
